package com.wrupple.vegetate.server.bussiness;

import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;
import com.wrupple.vegetate.domain.JDOPersistentFileMetadata;
import com.wrupple.vegetate.domain.PersistentFileMetadata;
import com.wrupple.vegetate.domain.exceptions.BussinessLayerException;
import com.wrupple.vegetate.domain.exceptions.CatalogException;
import com.wrupple.vegetate.server.bussiness.engine.CatalogEngine;
import com.wrupple.vegetate.server.bussiness.engine.CatalogFileSystem;
import com.wrupple.vegetate.server.dao.CatalogFileDAO;

public class CatalogFileSystemImpl implements CatalogFileSystem {

	@Autowired
	private CatalogFileDAO dao;
	@Autowired
	private CatalogEngine engine;

	@Override
	public String handleFileUpload(MultipartFile file) throws IOException, BussinessLayerException {
		String mime;
		String fileName;
		byte[] content;

		String fileId=null;
		
		if (!file.isEmpty()) {
			content = file.getBytes();
			fileId = dao.saveFile(content);

			mime = file.getContentType();
			fileName = file.getName();
			fileName = fileName.replace('\\', '-').replace('/', '-').replace(':', '-').replace(' ', '-');

			
			createMetadataEntry(fileId, fileName, mime, content);
		} 
		
		return fileId;

	}
	
	
	@Override
	public PersistentFileMetadata getFileMetadata(String fileId) throws CatalogException {
		PersistentFileMetadata regreso = (PersistentFileMetadata) engine.retriveEntry(JDOPersistentFileMetadata.CATALOG_ID, fileId);
		if(regreso ==null){
			regreso = createMetadataEntry(fileId, fileId, null, dao.loadFile(fileId));
		}
		return regreso;
	}
	

	@Override
	public void serveFile(String id, HttpServletRequest req, HttpServletResponse response) throws IOException {
		ServletOutputStream out = response.getOutputStream();
		byte[] file = dao.loadFile(id);
		out.write(file);
	}



	
	
	private JDOPersistentFileMetadata createMetadataEntry(String fileId, String fileName, String mime, byte[] content) throws BussinessLayerException{
		assert content !=null :"Will not create metadata of an empty file";
		byte[] thumbnail;
		byte[] icon;
		try {
			thumbnail = this.generateThumbnail(content);
			icon = this.generateIcon(content);
		} catch (Exception e) {
			// most likely not an image
			thumbnail = null;
			icon = null;
		}
		JDOPersistentFileMetadata mdata = new JDOPersistentFileMetadata();
		mdata.setIdAsString(fileId);
		mdata.setName(fileName);
		mdata.setMime(mime);
			engine.createEntry(JDOPersistentFileMetadata.CATALOG_ID, mdata);
		return mdata;
	}

	private byte[] generateIcon(byte[] bytes) {
		ImagesService imagesService = ImagesServiceFactory.getImagesService();
		Image oldImage = ImagesServiceFactory.makeImage(bytes);
		Transform resize = makeResize(oldImage, 30);
		Image newImage = imagesService.applyTransform(resize, oldImage);
		return newImage.getImageData();
	}

	private byte[] generateThumbnail(byte[] oldImageData) {
		ImagesService imagesService = ImagesServiceFactory.getImagesService();
		Image oldImage = ImagesServiceFactory.makeImage(oldImageData);
		Transform resize = makeResize(oldImage, 150);
		Image newImage = imagesService.applyTransform(resize, oldImage);
		return newImage.getImageData();
	}

	private com.google.appengine.api.images.Transform makeResize(Image img, int maxWidth) {
		int width = img.getWidth();
		int height = img.getHeight();
		if (width > maxWidth) {
			double ratio = (double) maxWidth / (double) width;
			width = (int) (width * ratio);
			height = (int) (height * ratio);
		}
		return ImagesServiceFactory.makeResize(width, height);
	}

	public void setDao(CatalogFileDAO dao) {
		this.dao = dao;
	}

	public CatalogFileDAO getDao() {
		return dao;
	}


	@Override
	public void createFileMetadata(String id,String name,boolean isImage) throws BussinessLayerException {
		JDOPersistentFileMetadata m = new JDOPersistentFileMetadata();
		m.setIdAsString(id);
			engine.createEntry(JDOPersistentFileMetadata.CATALOG_ID, m);
		
	}


	@Override
	public void serveImageThumbnail(String id, int largestSideLength, HttpServletRequest req,
			HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		
	}


}
